package models

import "log"

import "strconv"

type Category struct {
	Id          int64
	Parent      int64
	Name        string
	Ident       string
	Detail      string
	Sort_order  int
	Root_cat_id int64
}

func (t Category) TableName() string {
	return "zb3_service_catalogs"
}

func (tt *Category) getTagByIdent(ident string) int64 {
	t := new(Category)
	engine.Where("ident = ?", ident).Get(t)
	return t.Id
}

func (tt *Category) getMinSort(parentID int64) int {
	sql := "SELECT MIN(sort_order) AS min FROM `zb3_service_catalogs`WHERE parent = ?"
	result, err := engine.Query(sql, parentID)
	if err != nil {
		log.Println("get min sort_order error : ", err)
	}
	minOrderStr := string(result[0]["min"])
	if minOrderStr == "" {
		return 100
	} else {
		minOrder, err := strconv.Atoi(minOrderStr)
		if err != nil {
			log.Println("conv str to int error: ", err)
			return 100
		}
		return minOrder - 1
	}
}

// InsertTag 插入标签
func (tt Category) InsertTag(tagname string, p int64, types int, repeat bool) int64 {
	// tagIdent := GetIdent(tagname)
	// oldID := tt.getTagByIdent(tagIdent)
	// if oldID > 0 {
	// 	if !repeat {
	// 		return oldID
	// 	}
	// 	tagIdent = GetIdent(tagname + fmt.Sprintf("xxx%d", rand.Intn(1000)))
	// }
	if p < 0 {
		p = 0
	}
	// t := &Category{Name: tagname, Ident: tagIdent, Parent: p, Sort_order: 0, Root_cat_id: 0}
	sort1 := tt.getMinSort(p)
	log.Println("sort = ", sort1)
	t := &Category{Name: tagname, Parent: p, Sort_order: sort1, Detail: tagname, Root_cat_id: 0}
	_, err := engine.Insert(t)
	log.Printf("inserting tag  {id: %d;\tname: %s;\tparent: %d\t sort: %d\n", t.Id, t.Name, t.Parent, t.Sort_order)
	if err != nil {
		log.Println("insert tag error ", err)
	}
	return t.Id
}
